//
//  CoursePageViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/25.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonPageViewController.h"
#import "MineMessageListViewController.h"
#import "LessonStudyPageViewController.h"
#import "LessonCenterViewController.h"
#import "LessonItemViewController.h"
#import "LessonDetailViewController.h"
#import "LessonSearchResultViewController.h"
#import "ExercisesPageViewController.h"
#import "LessonHotCell.h"
#import "LessonClassMenuCell.h"
#import "LessonRecommendCell.h"
#import "LessonBannerView.h"
#import "LessonPageTitleView.h"
#import "LessonPageNavView.h"
#import "LessonUserlevelView.h"

#import "UserInfoModel.h"
#import "LessonPlanModel.h"
#import "LessonPageModel.h"
#import "LessonBannerModel.h"
#import "LessonSearchModel.h"

@interface LessonPageViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,LessonPageNavViewDelegate,LessonHotCellDelegate,LessonRecommendCellDelegate,LessonPageTitleViewDelegate,LessonClassMenuCellDelegate,LessonBannerViewDelegate>

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)LessonBannerView *bannerView;

@property (nonatomic,strong)LessonPageNavView *pageNavView;

@property (nonatomic,strong)LessonUserlevelView *levelView;

@property (nonatomic,strong)LessonPageModel *dtlModel;

@property (nonatomic,strong)NSMutableArray *bannerArray;

@property (nonatomic,strong)NSMutableArray *ownerIdArray;

@property (nonatomic,copy)NSArray *searchArray;

@property (nonatomic,strong)UIImageView *coverImgView;

//@property (nonatomic,strong)CAGradientLayer *gradientLayer;


@end

@implementation LessonPageViewController

- (LessonUserlevelView *)levelView{
    if (!_levelView) {
        _levelView = [[LessonUserlevelView alloc]init];
    }
    return _levelView;
}

- (LessonBannerView *)bannerView{
    if (!_bannerView) {
        _bannerView = [[LessonBannerView alloc]init];
        _bannerView.delegate = self;
    }
    return _bannerView;
}
//- (UIView *)coverView{
//    if (!_coverView) {
//        _coverView = [[UIView alloc]init];
//    }
//    return _coverView;
//}
- (UIImageView *)coverImgView{
    if (!_coverImgView) {
        _coverImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"course_cover_tag"]];
    }
    return _coverImgView;
}
- (NSMutableArray *)ownerIdArray{
    if (!_ownerIdArray) {
        _ownerIdArray = [NSMutableArray array];
    }
    return _ownerIdArray;
}
- (NSMutableArray *)bannerArray{
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}
//- (CAGradientLayer *)gradientLayer{
//    if (!_gradientLayer) {
//        _gradientLayer = [CAGradientLayer new];
//        //_gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor,(__bridge id)RGBA(0, 0, 0, 1)	.CGColor];
//        _gradientLayer.startPoint = CGPointMake(0, 0);
//        _gradientLayer.endPoint = CGPointMake(0, 1.0);
//        _gradientLayer.frame = CGRectMake(0, 0, kScreenW, 500);
//    }
//    return _gradientLayer;
//}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
   
    [self.bannerView setAdjustWhenControllerViewWillAppera];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
   
}

- (UIStatusBarStyle)preferredStatusBarStyle {

    if (self.tableView.contentOffset.y >= 20) {

        return UIStatusBarStyleDefault;
    }

    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {

    return UIStatusBarAnimationNone;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;

    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
            @zf_strongify(self)
            [self setNormalData];
        } cancelBlock:nil];
    }else{
        [self setNormalData];
    }
    [self registNote];

    // Do any additional setup after loading the view.
}

- (void)setNormalData{
    [self setUI];
    [self showDataLoadState];
    [self loadDataSource];
}

- (void)setUI{
        
    [self.view addSubview:self.coverImgView];
    
    self.navigationItem.leftBarButtonItem = nil;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
//
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.cl_height = 138.0f;
    self.tableView.mj_footer = footer;
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    self.tableView.mj_footer.hidden = YES;

    // 系统默认有32px的左右间距的
    self.pageNavView = [[LessonPageNavView alloc]init];
    self.pageNavView.backgroundColor = RGBA(255, 255, 255, 0);
    self.pageNavView.delegate = self;
    [self.view addSubview:self.pageNavView];

    [self.coverImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(kScreenW * 0.4 + 180);
    }];

    [self.pageNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        }else{
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
        }
        make.top.equalTo(self.view.mas_top);
        make.height.mas_equalTo(44 + GK_STATUSBAR_HEIGHT);
    }];

  
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
            make.bottom.equalTo(self.view.mas_bottom);
        }
        make.top.equalTo(self.pageNavView.mas_bottom);
    }];

    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDataSource];
    }];
    
    header.stateLabel.textColor = [UIColor whiteColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor whiteColor];
    header.loadingView.color = [UIColor whiteColor];

    self.tableView.mj_header = header;
//
    self.tableView.backgroundColor = [UIColor clearColor];

    self.view.backgroundColor = [UIColor whiteColor];
    
//    [self.coverView.layer insertSublayer:self.gradientLayer atIndex:0];
}
#pragma mark - 注册通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfo) name:@"updateUserInfoSource" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLessonPlanSource) name:@"updateStudyList" object:nil];

}

- (void)updateUserInfo{
    [self showDataLoadState];
    [self loadDataSource];
}

- (void)updateLessonPlanSource{
    //
    [self.tableView reloadData];
}

#pragma mark - 网络请求
- (void)loadDataSource{

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadPageListSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadUserPlanListSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadCourseBanner];
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadHotSearchSource];
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideDataLoadLoadState];
        self.tableView.mj_footer.hidden = NO;
        
        if (self.bannerArray.count != 0) {
            self.tableView.tableHeaderView = self.bannerView;
            // 设置bannerView
            self.bannerView.banners = self.bannerArray;
            [self.coverImgView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(kScreenW * 0.4 + 180);
            }];
        }else{
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 0.01f)];
            self.tableView.tableHeaderView = view;
            [self.coverImgView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(180);
            }];
        }
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];

        }
        [self.tableView reloadData];
    });
    
}



- (void)loadPageListSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetRecommendAndHot) parames:nil success:^(id responseObj) {
        self.dtlModel = [LessonPageModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadCourseBanner{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"scope"] = @2;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetBanner];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetBanner) parames:param success:^(id responseObj) {
        self.bannerArray = [LessonBannerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadUserPlanListSource{
    
    if (![RPAppManager isLogin]) {
        [RPAppManager deleteUserAllPlans];
        return;
    }
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(1);
    param[@"pageSize"] = @(9999);
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPlanList) parames:param success:^(id responseObj) {
        if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
            NSArray *arr = [LessonPlanModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][@"list"]];
            
            NSMutableArray *ownerIds = [NSMutableArray array];
            
            [arr enumerateObjectsUsingBlock:^(LessonPlanModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [ownerIds addObject:obj.id];
            }];
            
            [RPAppManager saveUserPlanIdsWithPlans:ownerIds];
            
        }else{
            [RPAppManager deleteUserAllPlans];
        }
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadHotSearchSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetHotSearch) parames:nil success:^(id responseObj) {
        self.searchArray = [LessonSearchModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        
        LessonSearchModel *model = [self.searchArray firstObject];

        [self.pageNavView setNavTitle:model.word];
        
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
#pragma mark - alpha
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
     
    [self setNeedsStatusBarAppearanceUpdate];
      	
    if (scrollView.contentOffset.y <= 0) {
        self.pageNavView.backgroundColor = RGBA(255, 255, 255, 0);
        [self.pageNavView updateAlpha:0];
     }
    
     if (scrollView.contentOffset.y > 0) {
                  
         CGFloat alpha = scrollView.contentOffset.y/150;
    
         self.pageNavView.backgroundColor = RGBA(255, 255, 255, alpha);
         
         self.coverImgView.alpha =  1 - alpha;
         
         [self.pageNavView updateAlpha:alpha];
     }
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (!self.dtlModel) {
        return 0;
    }
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return  MIN(self.dtlModel.hot.count,4);
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            LessonClassMenuCell *cell = [LessonClassMenuCell cellWithTableView:tableView];
            cell.delegate = self;
            return cell;
        }
    }
    if (indexPath.section == 1) {
        LessonHotCell *cell = [LessonHotCell cellWithTableView:tableView];
        [cell setCurrentModel:self.dtlModel.hot[indexPath.row]];
        [cell isHideLine:indexPath.row == self.dtlModel.hot.count - 1];
        cell.delegate = self;
        return cell;
     }
    if (indexPath.section == 2) {
        LessonRecommendCell *cell = [LessonRecommendCell cellWithTableView:tableView];
        [cell setRecommendSource:self.dtlModel.recommend];
        cell.delegate = self;
        return cell;
    }
 
    return [UITableViewCell new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return self.dtlModel.hot.count == 0?0.01f:66.0f;
    }
    if (section == 2) {
        return self.dtlModel.recommend.count == 0?0.01f:66.0f;
    }
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    LessonPageTitleView *titleView = [[LessonPageTitleView alloc]initWithTitleName:section == 1?@"热门课程":@"课程推荐" hideLine:section == 1];
    titleView.delegate = self;
    if (section == 1) {
        return self.dtlModel.hot.count == 0?nil:titleView;
    }
    if (section == 2) {
        return self.dtlModel.recommend.count ==0?nil:titleView;
    }

    return nil;
}


#pragma mark - CourseHotCellDelegate
- (void)addorRemoveCourseHotPlanAtCurrentModel:(LessonPageItemModel *)model{
    
    [MobClick event:@"lesson_hot_add_plan"];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
     
        NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
        [arr addObject:model.id];
        [RPAppManager saveUserPlanIdsWithPlans:arr];
        
        model.isSeleted = YES;
        // 取出对应的
        NSInteger idx = [self.dtlModel.hot indexOfObject:model];
        if (idx != -1) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:1];
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];
        
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)selectedCaurseAtCurrentModel:(LessonPageItemModel *)model{
    [MobClick event:@"lesson_hot_click"];
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"main_lesson_hot"}];
    [self nextCourseDetailWithlessonId:model.id];
}
#pragma mark  CourseClassMenuCellDelegate
- (void)showMenuListAtType:(NSInteger)type{
    if (self.dtlModel == nil) {
        return;
    }
    [MobClick event:@"lesson_search_click"];
    
    LessonCenterViewController *centerVC = [[LessonCenterViewController alloc]initWithSeachArray:self.searchArray andCurrentIndex:type];
    [self.navigationController pushViewController:centerVC animated:NO];
}
#pragma mark - CourseRecommendCellDelegate
- (void)addorRemoveCourseRecommendPlanAtCurrentModel:(LessonPageItemModel *)model{
    
    [MobClick event:@"lesson_recommend_add_plan"];
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
       
        model.isSeleted = YES;
        
        [self.ownerIdArray addObject:model.id];
        
        [RPAppManager saveUserPlanIdsWithPlans:self.ownerIdArray];
    
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
        
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];
   
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)didCourseDetailAtCurrentModel:(LessonPageItemModel *)model{
    [MobClick event:@"lesson_recommend_click"];
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"main_lesson_recommend"}];
    [self nextCourseDetailWithlessonId:model.id];
}

#pragma mark - CoursePageTitleViewDelegate
- (void)showMoreAtIndex:(NSInteger)index{
    NSString *title = index == 0?@"热门课程":@"课程推荐";
    XHCourseItemType type = XHCOURSEITEMRECOMMEND;
    if (index == 0) {
        type = XHCOURSEITEMHOT;
    }
    [MobClick event:@"lesson_recommend_more_click"];
    LessonItemViewController *itemVC = [[LessonItemViewController alloc]initWithItemType:type categoryId:-1 subjectId:-1];
    itemVC.title = title;
    [self.navigationController pushViewController:itemVC animated:YES];
}


- (void)showSearchMore{
    LessonSearchResultViewController *searchVC = [[LessonSearchResultViewController alloc]init];
    searchVC.hotArray = self.searchArray;
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)showCourseCenter{

    [MobClick event:@"lesson_center_click"];
    

    LessonStudyPageViewController *studyVC = [[LessonStudyPageViewController alloc]init];
    studyVC.searchArray = self.searchArray;

    [self.navigationController pushViewController:studyVC animated:YES];
}

- (void)popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - CourseBannerViewDelegate
-(void)didSelectAtIndex:(NSInteger)index{
    [MobClick event:@"lesson_banner_click"];
    
    LessonBannerModel *model = self.bannerArray[index];
    
    if (model.type.intValue != 3) {
        [[XHPushVCTool sharedXHPushVCTool] pushTargetVCWithUrl:model.url paramUrl:@""];
    }
}
- (void)updateHomePageNavColor:(UIColor *)color{
//    self.gradientLayer.colors = @[(__bridge id)RGBA(20, 24, 36, 1).CGColor,(__bridge id)RGBA(242, 250, 254, 1).CGColor,(__bridge id)UIColor.whiteColor.CGColor];
}
- (void)leaveCurrentViewController{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -跳转详情
- (void)nextCourseDetailWithlessonId:(NSNumber *)lessonId{
    LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
    dtlVC.lessonId = lessonId;
    [self.navigationController pushViewController:dtlVC animated:YES];
    __weak typeof(self)weakSelf = self;
    dtlVC.updateCourseStatus = ^(NSNumber * _Nonnull lessonId) {
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
    };
}
@end
